<?php

namespace Database\Seeders;

use Illuminate\Database\Seeder;
use DB;

class PermissionSeeder extends Seeder
{
    /**
     * 引值
     * @var string[]
     */
    public $keyValue = [
        'main' => '主页面查看',
        'opera' => '数据操作',
        'del' => '删除数据'
    ];
    /**
     * Seed the application's database.
     *
     * @return void
     */
    public function run()
    {
        DB::table('permission')->truncate(); // 清空表且新增
        //  列表
        $data = $this->handleReset([
            // 角色权限
            ['module' => 'admin','name' => '管理员','children' => ['main', 'opera', 'del']],
            ['module' => 'role','name' => '角色','children' => ['main', 'opera', 'del']],
            ['module' => 'menu','name' => '菜单','children' => ['main', 'opera', 'del']],
            ['module' => 'permission','name' => '功能权限','children' => ['main', 'opera', 'del']]
        ]);
        // 权限新增并且绑定
        DB::table('permission')->insert($data);
        //  获取id
        $ids = app(\App\Models\Permission::class)->pluck('id')->toArray();
        $role = app(\App\Models\Role::class)->find(1);
        $role->permissions()->sync($ids);
    }


    /**
     * 重构
     * @param $data
     * @return array
     */
    public function handleReset($data)
    {
        $result = [];
        $keyValue = $this->keyValue;
        foreach ($data as $value) {
            foreach ($value['children'] as $child) {
                $result[] = [
                    'module' => $value['module'],
                    'name' => $value['name'] . '-' . $keyValue[$child],
                    'code' => $value['module'] . '-' . $child,
                ];
            }
        }
        return $result;
    }
}
